package com.link.base.tencent.corpwx.externalcontact.util;

import com.alibaba.fastjson.JSONObject;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.HttpRequestUtil;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 外部联系人标准接口封装
 *
 * @author 欧阳振强
 * @date 2020/01/02
 */
public class ExternalContactUtil {
    /**获取配置了客户联系功能的成员列表接口*/
    private static final String GET_FOLLOW_USER_LIST_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=ACCESS_TOKEN";
    /**获取客户列表接口*/
    private static final String EXTERNAL_CONTACT_LIST_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=ACCESS_TOKEN&userid=USERID";
    /**获取客户详情接口*/
    private static final String EXTERNAL_CONTACT_INFO_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=ACCESS_TOKEN&external_userid=EXTERNAL_USERID";
    /**获取离职成员客户列表*/
    private static final String GET_UNASSIGNED_LIST_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_unassigned_list?access_token=ACCESS_TOKEN";
    /**离职成员再分配*/
    private static final String TRANSFER_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/transfer?access_token=ACCESS_TOKEN";
    /**获取联系客户统计数据*/
    private static final String GET_USER_BEHAVIOR_DATA_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?access_token=ACCESS_TOKEN";
    /**获取客户群统计数据*/
    private static final String GET_GROUP_CHAT_DATA_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/statistic?access_token=ACCESS_TOKEN";
    /**获取客户群列表*/
    private static final String GET_GROUP_CHAT_LIST_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=ACCESS_TOKEN";
    /**获取客户群详情*/
    private static final String GET_GROUP_CHAT_INFO_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=ACCESS_TOKEN";

     /**
     * 获取配置了客户联系功能的成员列表
     * 
     * @author 欧阳振强
     * @date 2020/01/02
     * @param accessToken 接口凭证
     */
    public static JSONObject getFollowUserList(String accessToken) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        String url = GET_FOLLOW_USER_LIST_API.replace("ACCESS_TOKEN", accessToken);
        String resultStr = HttpRequestUtil.sendGet(url, "");
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取客户列表
     *
     * @author 欧阳振强
     * @date 2019/1/2
     * @param accessToken 接口凭证
     * @param userId 成员Id
     */
    public static JSONObject getExternalContactList(String accessToken, String userId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(userId)) {
            throw new BasicServiceException("userId不能为空！");
        }
        String url = EXTERNAL_CONTACT_LIST_API.replace("ACCESS_TOKEN", accessToken).replace("USERID", userId);
        String resultStr = HttpRequestUtil.sendGet(url, "");
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取客户明细
     *
     * @author 欧阳振强
     * @date 2019/1/2
     * @param accessToken 接口凭证
     * @param externalUserId 外部联系人Id
     */
    public static JSONObject getExternalContact(String accessToken, String externalUserId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(externalUserId)) {
            throw new BasicServiceException("外部联系人Id不能为空！");
        }
        String url = EXTERNAL_CONTACT_INFO_API.replace("ACCESS_TOKEN", accessToken).replace("EXTERNAL_USERID", externalUserId);
        String resultStr = HttpRequestUtil.sendGet(url, "");
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取离职成员的客户列表
     * 返回数据按离职时间的降序排列，当page_id为1，page_size为100时，表示取第101到第200条记录
     *
     * @author 欧阳振强
     * @date 2019/1/2
     * @param accessToken 接口凭证
     * @param pageId 分页查询，要查询页号，从0开始
     * @param pageSize 每次返回的最大记录数，默认为1000，最大值为1000
     */
    public static JSONObject getUnassignedList(String accessToken, String pageId, String pageSize) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        String url = GET_UNASSIGNED_LIST_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("page_id", pageId);
        obj.put("page_size", pageSize);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 离职成员再分配
     *
     * @author 欧阳振强
     * @date 2019/1/2
     * @param accessToken 接口凭证
     * @param externalUserId 外部联系人的userId
     * @param handoverUserId 离职成员的userId
     * @param takeoverUserId 接替成员的userId
     */
    public static JSONObject transferExternalContact(
        String accessToken,  String externalUserId, String handoverUserId, String takeoverUserId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(externalUserId)) {
            throw new BasicServiceException("外部联系人Id不能为空！");
        }
        if (StringUtils.isBlank(handoverUserId)) {
            throw new BasicServiceException("离职成员的userId不能为空！");
        }
        if (StringUtils.isBlank(takeoverUserId)) {
            throw new BasicServiceException("接替成员的userId不能为空！");
        }
        String url = TRANSFER_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("external_userid", externalUserId);
        obj.put("handover_userid", handoverUserId);
        obj.put("takeover_userid", takeoverUserId);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取联系客户统计数据
     * 企业可通过此接口获取成员联系客户的数据，包括发起申请数、新增客户数、聊天数、发送消息数和删除/拉黑成员的客户数等指标
     *
     * @author 欧阳振强
     * @date 2019/2/6
     * @param accessToken 接口凭证
     * @param userIdList 用户ID列表
     * @param partyIdList 部门ID列表
     * @param startTime 数据起始时间【必填】
     * @param endTime 数据结束时间【必填】
     */
    public static JSONObject getUserBehaviorData(String accessToken, List<String> userIdList, List<String> partyIdList,
                                                 String startTime, String endTime) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        userIdList = userIdList == null ? new ArrayList<>() : userIdList;
        partyIdList = partyIdList == null ? new ArrayList<>() : partyIdList;
        if (userIdList.size() <= 0 && partyIdList.size() <= 0) {
            throw new BasicServiceException("userId和partyId不可同时为空！");
        }
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            throw new BasicServiceException("数据起始时间和结束时间不能为空！");
        }
        String url = GET_USER_BEHAVIOR_DATA_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        if (userIdList.size() > 0) {
            obj.put("userid", userIdList);
        }
        if (partyIdList.size() > 0) {
            obj.put("partyid", partyIdList);
        }
        obj.put("start_time", startTime);
        obj.put("end_time", endTime);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取客户群统计数据
     * 获取指定日期全天的统计数据
     *
     * @author 欧阳振强
     * @date 2019/3/13
     * @param accessToken 接口凭证
     * @param userIdList 用户ID列表
     * @param partyIdList 部门ID列表
     * @param startTime 起始时间【必填】
     * @param orderBy 排序方式 1 - 新增群的数量；2 - 群总数；3 - 新增群人数；4 - 群总人数，默认为1
     * @param orderAsc 是否升序 0 - 否；1 - 是，默认降序
     * @param offset 分页 - 偏移量
     * @param limit 分页 - 预期请求的数据量
     */
    public static JSONObject getGroupChatData(String accessToken, List<String> userIdList, List<String> partyIdList,
                                              String startTime, String orderBy, String orderAsc, String offset, String limit) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        userIdList = userIdList == null ? new ArrayList<>() : userIdList;
        partyIdList = partyIdList == null ? new ArrayList<>() : partyIdList;
        if (StringUtils.isBlank(startTime)) {
            throw new BasicServiceException("数据起始时间不能为空！");
        }
        String url = GET_GROUP_CHAT_DATA_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("day_begin_time", startTime);
        JSONObject ownerFilter = new JSONObject();
        if (userIdList.size() > 0) {
            ownerFilter.put("userid_list", userIdList);
        }
        if (partyIdList.size() > 0) {
            ownerFilter.put("partyid_list", partyIdList);
        }
        obj.put("owner_filter", ownerFilter);
        if (StringUtils.isNotBlank(orderBy)) {
            obj.put("order_by", orderBy);
        }
        if (StringUtils.isNotBlank(orderAsc)) {
            obj.put("order_asc", orderAsc);
        }
        if (StringUtils.isNotBlank(offset)) {
            obj.put("offset", offset);
        }
        if (StringUtils.isNotBlank(limit)) {
            obj.put("limit", limit);
        }
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取客户群聊列表
     *
     * @author 欧阳振强
     * @date 2019/3/18
     * @param accessToken 接口凭证
     * @param userIdList 用户ID列表
     * @param partyIdList 部门ID列表
     * @param statusFilter 群状态过滤，0 - 普通列表；1 - 离职待继承；2 - 离职继承中；3 - 离职继承完成；默认为0
     * @param offset 分页 - 偏移量【必填】
     * @param limit 分页 - 预期请求的数据量，取值范围 1 ~ 1000【必填】
     */
    public static JSONObject getGroupChatList(String accessToken, List<String> userIdList, List<String> partyIdList,
                                              String statusFilter, String offset, String limit) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(offset)) {
            throw new BasicServiceException("偏移量不能为空！");
        }
        if (StringUtils.isBlank(limit)) {
            throw new BasicServiceException("预期请求的数据量不能为空！");
        }
        userIdList = userIdList == null ? new ArrayList<>() : userIdList;
        partyIdList = partyIdList == null ? new ArrayList<>() : partyIdList;
        String url = GET_GROUP_CHAT_LIST_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        if (StringUtils.isNotBlank(statusFilter)) {
            obj.put("status_filter", statusFilter);
        }
        JSONObject ownerFilter = new JSONObject();
        if (userIdList.size() > 0) {
            ownerFilter.put("userid_list", userIdList);
        }
        if (partyIdList.size() > 0) {
            ownerFilter.put("partyid_list", partyIdList);
        }
        obj.put("owner_filter", ownerFilter);
        obj.put("offset", offset);
        obj.put("limit", limit);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 获取客户群聊详情
     *
     * @author 欧阳振强
     * @date 2019/3/18
     * @param accessToken 接口凭证
     * @param chatId 客户群ID
     */
    public static JSONObject getGroupChatInfoById(String accessToken, String chatId) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(chatId)) {
            throw new BasicServiceException("客户群ID不能为空！");
        }
        String url = GET_GROUP_CHAT_INFO_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("chat_id", chatId);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }
}
